package edu.nf.supermarket.service.impl;

import edu.nf.supermarket.entity.Coupon;
import edu.nf.supermarket.entity.User;
import edu.nf.supermarket.exception.LoginException;
import edu.nf.supermarket.mapper.CouponMapper;
import edu.nf.supermarket.mapper.UserCouponMapper;
import edu.nf.supermarket.mapper.UserMapper;
import edu.nf.supermarket.service.CouponService;
import edu.nf.supermarket.service.UserCouponService;
import edu.nf.supermarket.service.UserService;
import edu.nf.supermarket.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @author yjj
 * @date 2025-05-20
 */
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCouponService userCouponService; // 注册优惠卷服务
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    // 手机号正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);

    public static boolean isValidPhone(String phone) {
        return phone != null && PHONE_PATTERN.matcher(phone).matches();
    }

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    @Override
    public String login(String phone, String password) {
        if (phone == null || phone.isEmpty()) {
            throw new LoginException(10001, "手机号或密码不能为空");
        }
        User login = userMapper.findUserByPhone(phone);
        if (password.isEmpty() && !login.getPassword().equals(password)) {
            throw new LoginException(1002, "账号或密码错误");
        }
        return TokenUtil.createToken(login.getUserId());
    }

    @Override
    public void addUser(User user) {
        User user1 = userIsEmpty(user);
        userMapper.addUser(user1);
    }

    @Override
    public void addAvatar(Integer userId, String avatar) {
        userMapper.addAvatar(userId, avatar);
    }

    @Override
    public User findUserByPhone(String phone) {
        return userMapper.findUserByPhone(phone);
    }

    @Override
    public User findUserBuId(Integer userId) {
        return userMapper.findUserById(userId);
    }

    @Override
    public Integer getUserCount() {
        return userMapper.getUserCount();
    }

    @Override
    public Map<String, Long> countUserTypes() {
        // 设置分析参数
        Date currentDate = new Date();  // 当前日期
        int activeDays = 30;            // 活跃周期
        int sleepDays = 90;             // 沉睡周期

        return userMapper.countUserTypes(currentDate, activeDays, sleepDays);
    }

    /**
     * 检查是否为新用户
     * 逻辑是：如果没有领取过新人优惠卷，则为新用户
     * @param userId
     * @return
     */
    @Override
    public boolean isNewUserForCouponCheck(Integer userId) {
        Coupon newUserCoupon = couponMapper.findNewUserCouponByName("新用户优惠券");
        if (newUserCoupon == null){
            System.out.println("新人优惠卷模版未找到，无法检查是否是新用户");
            return false;
        }
        int count = userCouponMapper.countUserCouponByUserIdAndCouponId(userId, newUserCoupon.getCouponId());
        return count == 0;
    }

    /**
     * 用户信息校验方法（如果用户没有写入昵称， 则自动填写用户名，头像后面再写）
     *
     * @param user
     * @return
     */
    public User userIsEmpty(User user) {
        System.out.println(user.toString());
        if (user == null) {
            throw new LoginException(10001, "手机号或密码不能为空");
        }
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            throw new LoginException(10001, "手机号或密码不能为空");
        }
        if (!isValidPhone(user.getPhone())) {
            throw new LoginException(10004, "手机号码错误");
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new LoginException(10001, "手机号或密码不能为空");
        }
        if (user.getUserName() == null || user.getUserName().isEmpty()) {
            user.setUserName(createUsername());
        }
        return user;
    }

    public static String createUsername() {
        return "用户" + UUID.randomUUID().toString();
    }


}
